from django.shortcuts import render, redirect
# 导包
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
# 导入类视图
from django.views import View

# from myapp.models import User
import json
from django.core.serializers import serialize
from rest_framework.response import Response
from rest_framework.views import APIView
# 导入加密库
import hashlib
# 导入图片库
# 绘画库
from PIL import ImageDraw
# 字体库
from PIL import ImageFont
# 图片库
from PIL import Image
# 随机库
import random
# 文件流
import io

import requests

# 导入上传文件夹配置
from mydjango.settings import UPLOAD_ROOT
import os

# 导入原生sql模块
from django.db import connection

import jwt

# 导入redis数据库
import redis

# 导入时间模块
import time

# 导入公共目录变量
from mydjango.settings import BASE_DIR

# 导包
from django.db.models import Q, F

# 导入dwebsocket的库
from dwebsocket.decorators import accept_websocket
import uuid

from myapp.models import User

#导入钉钉三方登录所需库
import hmac
import base64
from hashlib import sha256
import urllib

#创建注册视图类
class Register_Week(APIView):
    def get(self,request):
        username = request.GET.get('username')
        password = request.GET.get('password')

        user = User.objects.filter(username=username).first()
        if user:
            #如果存在
            res = {}
            res['code'] = 405
            res['message'] = "用户名已存在"

            return Response(res)
        else:
            #不存在则创建新账号
            user = User(username=username,password=password,img='',type=0)
            user.save()

            res = {}
            res['code'] = 200
            res['message'] = "注册成功"

            return Response(res)

#登录接口
class Login_Week(APIView):
    def get(self,request):
        username = request.GET.get('username')
        password = request.GET.get('password')
        #验证账号密码
        user = User.objects.filter(username=username,password=password).first()
        if user:
            res = {}
            res['code'] = 200
            res['message'] = '登陆成功'

            return Response(res)
        else:
            res = {}
            res['code'] = 405
            res['message'] = '用户名或密码错误'

            return Response(res)


#构造钉钉回调方法
def ding_back(request):

    #获取code
    code = request.GET.get("code")

    t = time.time()
    #时间戳
    timestamp = str((int(round(t * 1000))))
    appSecret ='ly-AzMKMmCKQP3geaILT_An32kEfKO3HeOtApy5CgKwjytevVZC0WYsT2gxMB160'
    #构造签名
    signature = base64.b64encode(hmac.new(appSecret.encode('utf-8'),timestamp.encode('utf-8'), digestmod=sha256).digest())
    #请求接口，换取钉钉用户名
    payload = {'tmp_auth_code':code}
    headers = {'Content-Type': 'application/json'}
    res = requests.post('https://oapi.dingtalk.com/sns/getuserinfo_bycode?signature='+urllib.parse.quote(signature.decode("utf-8"))+"&timestamp="+timestamp+"&accessKey=dingoaukgkwqknzjvamdqh",data=json.dumps(payload),headers=headers)

    res_dict = json.loads(res.text)
    print(res_dict)
    # return HttpResponse(res.text)
    #排重
    user = User.objects.filter(username=str(res_dict['user_info']['nick'])).first()
    ding_name = ''
    ding_id = ''

    if user:
        ding_name = str(res_dict['user_info']['nick'])
        ding_id = user.id
    else:
        user = User(username=str(res_dict['user_info']['nick']),password=',img=',type=0)
        user.save()

        user = User.objects.filter(username=str(res_dict['user_info']['nick'])).first()

        ding_name = str(res_dict['user_info']['nick'])
        ding_id = user.id


    return redirect('http://localhost:8080?ding_name=' + str(res_dict['user_info']['nick']) + "&ding_id=" + str(ding_id))








